package com.wx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wx.pojo.CreditDetails;
import com.wx.pojo.StuInfo;
import com.wx.service.CreditDetailsService;
import com.wx.service.StuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/stu")
public class StuController {

    @Autowired
    private CreditDetailsService creditDetailsService;

    @PostMapping("/ExportExcel")
    public void ExportExcel() {
        // 设置文件导出的路径
        String realPath = "E://wsfile/";
        File folder = new File(realPath);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String fileName = realPath  + "User" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(fileName, StuInfo.class).sheet("用户表").doWrite(creditDetailsService.list());
    }

//    public List data() {
//        //查询用户表,具体service层实现就不写了
//        List<StuInfo> list1 = loginService.findUser();
//        return list1;
//    }

    @PostMapping("/ImportExcel")
    public void ImportExcel(MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()) {
            return;
        }
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(multipartFile.getInputStream(), CreditDetails.class, new PageReadListener<CreditDetails>(dataList -> {
            for (CreditDetails creditDetails : dataList) {
                //将导入的数据用mybatisPlus一个个添加进数据库
                try{
                    LambdaQueryWrapper<CreditDetails> qw = new LambdaQueryWrapper<>();
                    qw.eq(CreditDetails::getStudentId,creditDetails.getStudentId());
                    creditDetailsService.save(creditDetails);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        })).sheet().doRead();
    }
}
